import {View, Text, Button} from '@tarojs/components';
import {Cell} from "@antmjs/vantui";
import {useCallback, useState} from "react";
import LogUtils from "@/utils/log";
import Utils from "@/utils/common";
import {getPhoneApi} from "@/common/apis/home_datasource";
import JsonUtils from "@/utils/json_utils";
import {PhoneInfoResponse} from "@/common/apis/model";

function GetPhoneButton(pros) {

  const [phone, setPhone] = useState<String>()
  const handleGetPhoneNumber = useCallback(async (e) => {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      const {encryptedData, iv, code} = e.detail;
      LogUtils.error(`encryptedData=${encryptedData} iv=${iv} code=${code}`)
      const res = await getPhoneApi({code: code});
      const data = JsonUtils.parse<PhoneInfoResponse>(res)
      if (data.errcode === 0) {
        setPhone(data.phone_info.phoneNumber)
        pros.phone.current = data.phone_info.phoneNumber
      } else {
        Utils.showErrorToast(data.errmsg)
      }
    }
  }, [pros.phone]);
  return (
    <View>
      <Cell renderIcon={<Text>绑定手机号：</Text>} renderTitle={<Button
        openType='getPhoneNumber'
        onGetPhoneNumber={handleGetPhoneNumber}
      >
        {Utils.isNotBlank(phone) ? phone : ' 获取微信手机号'}
      </Button>}
      />
    </View>
  );
}

export default GetPhoneButton;
